#include <iostream>
#include <functional>
#include <memory>
#include <thread>
#include <future>
#include <mutex>
#include <condition_variable>
#include <vector>

class threadpool
{
public:
    using Functor = std::function<void(void)>;
    threadpool(int thr_count = 1)
    :_stop(false)
    {
        for (int i = 0; i < thr_count; i++)
        {
            _threads.emplace_back(&threadpool::entry, this);
        }
    }
    template<typename F, typename ...Args>
    auto push(F&& func, Args&& ...args) -> std::future<decltype(func(args...))> // decltype执行函数推导出函数返回类型
    {
        // 封装packaged_task任务
        using return_type = decltype(func(args...));
        auto tmp_func = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
        auto task = std::make_shared<std::packaged_task<return_type()>>(tmp_func); // 已经把参数全部bind了
        std::future<return_type> fu = task->get_future();
        {
            std::unique_lock<std::mutex> lock(_mutex);
            // 将构造出的匿名函数对象抛入任务池
            _taskpool.push_back( [task](){ (*task)(); } );
            _cv.notify_one();
        }
        return fu;
    }
    void stop()
    {
        if (_stop == true) return;
        _stop = true;
        _cv.notify_all();
        for (auto& thread : _threads)
        {
            thread.join();
        }
    }
    ~threadpool()
    {
        stop();
    }
private:
    void entry()
    {
        while (!_stop)
        {
            std::vector<Functor> tmp_taskpool;
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _cv.wait(lock, [this](){ return _stop || !_taskpool.empty(); });
                tmp_taskpool.swap(_taskpool);
            }
            for(auto& task : tmp_taskpool)
            {
                task();
            }
        }
    }
private:
    std::atomic<bool> _stop;
    std::vector<Functor> _taskpool;
    std::mutex _mutex;
    std::condition_variable _cv;
    std::vector<std::thread> _threads;
};

int Add(int num1, int num2)
{
    return num1 + num2;
}

int main()
{
    threadpool pool;
    for (int i = 0; i < 10; i++)
    {
        std::future<int> fu = pool.push(Add, 11, i);
        std::cout << fu.get() << std::endl;
    }
    pool.stop();

    return 0;
}